package com.itheima.goods.controller;

import com.itheima.goods.pojo.Goods;
import com.itheima.goods.service.GoodsService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wang
 * @description
 * @date 2021/7/29 12:45
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping
    public Result findAll() {
        List<Goods> goods = goodsService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", goods);
    }

    @GetMapping("/search/{page}/{size}")
    public Result findPage4Get(
            @PathVariable("page") Integer page,
            @PathVariable("size") Integer size
    ) {
        PageResult<Goods> pageResult = goodsService.findPage4Get(page, size);
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @PostMapping("/search/{page}/{size}")
    public Result findPage4Post(
            @PathVariable("page") Integer page,
            @PathVariable("size") Integer size,
            @RequestBody Goods goods
    ) {
        PageResult<Goods> pageResult = goodsService.findPage4Post(page, size, goods);
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @GetMapping("/{id}")
    public Result<Goods> findById(
            @PathVariable("id") Integer id
    ) {
        Goods goods = goodsService.findById(id);
        return new Result<>(true,StatusCode.OK,"查询成功",goods);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(
            @PathVariable("id") Integer id
    ) {
        boolean delete = goodsService.deleteById(id);
        return new Result(delete,StatusCode.OK,"删除成功",null);
    }

    @PostMapping
    public Result add(@RequestBody Goods goods) {
        boolean add = goodsService.add(goods);
        return new Result(add,StatusCode.OK,"添加成功",null);
    }

    @PutMapping("/{id}")
    public Result update(@RequestBody Goods goods,
                         @PathVariable("id") Integer id
                         ) {
        boolean update = goodsService.updateGoods(goods,id);
        return new Result(update,StatusCode.OK,"修改成功",null);
    }

    @PutMapping("/buy")
    public Result buy(@RequestParam(value = "goodId") Integer goodId,
                      @RequestParam(value = "buyNum") Integer buyNum){
        return goodsService.buy(goodId,buyNum);
    }
}
